package com.demo.web.interceptor;


import com.demo.web.config.Login;
import com.demo.web.model.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Component
@Aspect
@Order(0)
//@ConditionalOnClass({Around.class, ReflectionWorld.class})
public class LoginInterceptor implements Order{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public LoginInterceptor() {
    }

    @Pointcut("@annotation(com.demo.web.config.Login)")
    public void p1() {
    }

    @Before("p1()")
    public void before() {

    }

    @Around("p1()")
    public Object userAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature s = joinPoint.getSignature();
        MethodSignature ms = (MethodSignature) s;
        Method m = ms.getMethod();
        Login login = m.getAnnotation(Login.class);
        //这里拿到了login的注解，可以读取注解的内容，做对应的处理
        //这里只有一个version字段
        String version = login.version();
        //这里可以处理登录信息了。
        //如果失败，直接返回失败信息就可以了。
        String token = request.getHeader("Authorization");
        if (StringUtils.equalsAnyIgnoreCase(token, "123456")) {
            //处理好了之后，就返回即可。
            return joinPoint.proceed();
        } else {
            return HttpResponse.fail(401, "登录失败。");
        }
    }

    @Override
    public int value() {

        return 0;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return Order.class;
    }
}
